package cn.springcloud.alibaba.security.handler;

import cn.springcloud.alibaba.core.base.BaseResponse;
import cn.springcloud.alibaba.core.util.RequestUtil;
import cn.springcloud.alibaba.core.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
		log.info("登录失败:{}", e.getMessage(), e);

		BaseResponse result;
		if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
			result = new BaseResponse(401, "账户名或者密码输入错误!");
		} else if (e instanceof LockedException) {
			result = new BaseResponse(401, "账户被锁定，请联系管理员!");
		} else if (e instanceof CredentialsExpiredException) {
			result = new BaseResponse(401, "密码过期，请联系管理员!");
		} else if (e instanceof AccountExpiredException) {
			result = new BaseResponse(401, "账户过期，请联系管理员!");
		} else if (e instanceof DisabledException) {
			result = new BaseResponse(401, "账户被禁用，请联系管理员!");
		} else {
			result = new BaseResponse(401, "登录失败!");
		}

		ResponseUtil.outputJsonResponse(response, result);
	}
}
